import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import requests
import psutil

# 发件人邮箱账号
sender_email = "Outgoing email address"
# 发件人邮箱授权码（不是密码）
sender_password = "Authorization code"
# 收件人邮箱
receiver_email = "Receiving address"

# 用于获取公网IP的API列表
api_urls = ["http://ip.3322.net", "http://ip.qaros.com", "http://ip.cip.cc", "myip.ipip.net"]
public_ip = "无法获取IP地址"

for url in api_urls:
    try:
        response = requests.get(url)
        if response.status_code == 200:
            if url == "http://ip.cip.cc":
                public_ip = response.text.splitlines()[0].split(": ")[1]
            elif url == "myip.ipip.net":
                public_ip = response.text.split("：")[1].strip()
            else:
                public_ip = response.text.strip()
            break
    except requests.RequestException:
        continue

# 获取联网方式
net_io_counters = psutil.net_io_counters(pernic=True)
network_interface = None
for interface, counters in net_io_counters.items():
    if counters.bytes_sent > 0 or counters.bytes_recv > 0:
        network_interface = interface
        break

connection_type = "未知联网方式"
if network_interface:
    if any(keyword in network_interface.lower() for keyword in ["eth", "en", "em"]):
        connection_type = "以太网联网"
    elif "wlan" in network_interface.lower():
        connection_type = "WiFi联网"
    elif "bluetooth" in network_interface.lower():
        connection_type = "蓝牙联网"

# 创建邮件对象
msg = MIMEMultipart()
msg['Subject'] = "来自WAP，您的计算机有一次异常登录信息"
msg['From'] = sender_email
msg['To'] = receiver_email

# 邮件正文，添加IP地址信息和联网方式信息并另起一行显示
body = f"这是一封由WAP触发的异常登录信息的邮件，包含摄像头拍摄附件。\n当前计算机对外的网络IP地址是：{public_ip}\n当前联网方式是：{connection_type}"
msg.attach(MIMEText(body, 'plain'))

# 指定文件夹路径
folder_path = r'C:\wap\photo'  # 请替换为实际的文件夹路径
latest_file = None
latest_time = 0
for root, dirs, files in os.walk(folder_path):
    for file in files:
        file_path = os.path.join(root, file)
        file_time = os.path.getmtime(file_path)
        if file_time > latest_time:
            latest_time = file_time
            latest_file = file_path

if latest_file:
    try:
        with open(latest_file, "rb") as f:
            part = MIMEApplication(f.read(), Name=os.path.basename(latest_file))
            part['Content-Disposition'] = f'attachment; filename="{os.path.basename(latest_file)}"'
            msg.attach(part)
    except FileNotFoundError:
        pass
else:
    print("文件夹中没有照片")

# 连接到QQ邮箱的SMTP服务器并发送邮件
# 使用465端口和SSL连接
try:
    with smtplib.SMTP_SSL('smtp.qq.com', 465) as server:
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, receiver_email, msg.as_string())
except smtplib.SMTPException:
    pass
